package com.dangz.dans.service;

import com.dangz.dans.dao.SubscribeInfoRepository;
import com.dangz.dans.entity.CommonReqEntity;
import com.dangz.dans.model.wx.SubscribeInfo;
import com.dangz.dans.model.req.SubscribeInfoPageReq;
import com.dangz.dans.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * SubscribeInfoServiceImpl 实现类
 * @author dangz
 * @since 2018/2/1 16:21
 */
@Service
public class SubscribeInfoServiceImpl {
    @Autowired
    private SubscribeInfoRepository subscribeInfoRepository;

    /**
     * MethonName: save
     * 保存
     * @params:  [info]
     * @return:  com.dangz.dans.model.other.wx.SubscribeInfo
     *
     * @author: dangz
     * @since: 2018/2/1 16:23
     */
    public SubscribeInfo save(SubscribeInfo info) {
        return subscribeInfoRepository.save(info);
    }
    public void save(List<SubscribeInfo> infos) {
        subscribeInfoRepository.save(infos);
    }

    /**
     * MethonName: listPage
     * 分页
     * @params:  [req]
     * @return:  com.dangz.dans.utils.PageUtil
     *
     * @author: dangz
     * @since: 2018/2/1 16:29
     */
    public PageUtil listPage(CommonReqEntity<SubscribeInfoPageReq> req){
        Pageable pageable = new PageRequest(req.getCurPage() - 1, req.getPageSize(),
                new Sort(Sort.Direction.DESC, "subscribe_time"));
        Specification<SubscribeInfo> specification = new Specification<SubscribeInfo>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotEmpty(req.getRequestEntity().getName())) {
                    list.add(cb.like(root.get("nickname").as(String.class), "%" + req.getRequestEntity().getName() + "%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return query.where(list.toArray(p)).getRestriction();
            }
        };
        return new PageUtil ( subscribeInfoRepository.findAll(specification, pageable) );
    }

    /**
     * MethonName: findByOpenidAndTo
     *
     * @params:  [openid, to]
     * @return:  com.dangz.dans.model.wx.SubscribeInfo
     *
     * @author: dangz
     * @since: 2018/2/2 11:30
     */
    public SubscribeInfo findByOpenidAndPid(String openid, String to){
        return subscribeInfoRepository.findByOpenidAndPid(openid, to);
    }
}
